using Commons.Models.Stats;
using Commons.Utils;
using System.Collections.Generic;
using System;

namespace Commons.Models.Definitions
{
	[Serializable]
	public class LeveledStatDefinition : IStatDefinition
	{
		private RangeDictionary<int, LevelDefinition> levels = new RangeDictionary<int, LevelDefinition>(true);
		private int lastLevelLoop;

		public System.Collections.Generic.SortedDictionary<int,LevelDefinition>.ValueCollection DefinedLevels
		{
			get
			{
				return levels.Values;
			}
		}

		public IStatUnit Unit { get; private set; }

		public LeveledStatDefinition(IStatUnit unit)
			: this (unit, 0)
		{
		}

		public LeveledStatDefinition(IStatUnit unit, int lastLevelLoop)
		{
			this.Unit = unit;
			this.lastLevelLoop = lastLevelLoop;
		}

		public LevelDefinition GetLevelByValue(int value)
		{
			LevelDefinition level = levels.Get(value);
			if (level.Num < levels.Count || lastLevelLoop == 0)
			{
				return level;
			}
			else
			{
				return GetLevelByNum(level.Num + ((value - level.Required) / lastLevelLoop));
			}
		}

		public LevelDefinition GetLevelByNum(int num)
		{
			if (num <= levels.Count)
			{
				return levels[num - 1];
			}
			else if (lastLevelLoop > 0)
			{
				LevelDefinition lastLevel = levels[levels.Count - 1];

				return new LevelDefinition(num, lastLevel.Required + lastLevelLoop * (num - lastLevel.Num), lastLevel.Reward);
			}
			else
			{
				return null;
			}
		}

		public void AddLevel(LevelDefinition level)
		{
			levels.Add(level.Required, level);
		}
	}
}
